package com.example.order.service.impl;

import com.example.order.feign.AccountClient;
import com.example.order.feign.EasyIdClient;
import com.example.order.feign.StorageClient;
import com.example.order.mapper.OrderMapper;
import com.example.order.pojo.Order;
import com.example.order.service.OrderService;
import com.example.order.tcc.OrderTccAction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;

    @Autowired
    private OrderTccAction orderTccAction;

    @GlobalTransactional
    @Override
    public void create(Order order) {
        Long orderId = Long.valueOf(easyIdClient.nextId("order_business"));
        order.setId(orderId);

        //orderMapper.create(order);
        orderTccAction.prepare(
                null, //在aop代码中，null会自动创建上下文对象
                orderId,
                order.getUserId(),
                order.getProductId(),
                order.getCount(),
                order.getMoney());
        //减库存
        storageClient.decease(order.getProductId(), order.getCount());
        //减少money
        accountClient.decrease(order.getUserId(), order.getMoney());
    }
}
